<template>
  <div class="common-layout linear-gradient">
    <el-container>
      <el-header class="header-container">
        <div class="headerTitle">查询条件</div>
        <div class="header-content">
          <el-form :model="headerSearchForm" label-width="auto" class="header-search-form">
            <el-form-item label="产线">
              <el-input v-model="headerSearchForm.productionLine" placeholder="请输入产线" />
            </el-form-item>
            <el-form-item label="变量描述">
              <el-input v-model="headerSearchForm.l1VariableDescription" placeholder="请输入变量描述" />
            </el-form-item>
            <el-form-item label="变量名">
              <el-input v-model="headerSearchForm.l1VariableName" placeholder="请输入变量名" />
            </el-form-item>
            <el-form-item label="变量别名">
              <el-input v-model="headerSearchForm.l1VariableAlias" placeholder="请输入变量别名" />
            </el-form-item>
            <el-form-item label="数据源">
              <el-select v-model="dataSourceType" placeholder="数据源" clearable style="width: 240px">
                <el-option v-for="item in dataSourceTypeOptions" :key="item.value" :label="item.label" :value="item" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="header-buttons">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button type="primary" @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleAdd">添加</el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="table-container-main">
          <!-- {{ tableData[0].indocno }} -->
          <el-table
            :data="tableData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column prop="serialNumber" label="序号" fixed="left">
              <template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productionLine" label="产线" />
            <el-table-column prop="areaCode" label="区域代码" />
            <el-table-column prop="deviceCode" label="设备代码" />
            <el-table-column prop="l1VariableName" label="变量名" />
            <el-table-column prop="l1VariableAlias" label="变量别名" />
            <el-table-column prop="l1VariableDescription" label="变量描述" />
            <el-table-column label="数据源">
              <template #default="scope">
                <span>{{ dataSourceTypeOptions[Number(scope.row.outDataSource - 1) <= 0 ? 0 : Number(scope.row.outDataSource - 1)].label }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="triggerFlag" label="触发标记" />
            <el-table-column prop="variableProperty" label="变量属性" />
            <el-table-column prop="enable" label="是否启用" />
            <el-table-column prop="toc" label="创建时间" />
            <el-table-column prop="tom" label="修改时间" />
            <el-table-column label="操作" fixed="right" width="240">
              <template #default="scope">
                <el-button type="warning" @click="handleEdit(scope.row)">修改</el-button>
                <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="handleClose" ref="dialogRef" @closed="cancel">
    <el-form :model="dialogForm" label-width="auto" :rules="dialogFormRule" ref="dialogFormRef">
      <el-form-item label="产线">
        <el-input v-model="dialogForm.productionLine" placeholder="请输入产线" />
      </el-form-item>
      <el-form-item label="区域代码">
        <el-input v-model="dialogForm.areaCode" placeholder="请输入区域代码" />
      </el-form-item>
      <el-form-item label="设备代码">
        <el-input v-model="dialogForm.deviceCode" placeholder="请输入设备代码" />
      </el-form-item>
      <el-form-item label="变量名">
        <el-input v-model="dialogForm.l1VariableName" placeholder="请输入变量名" />
      </el-form-item>
      <el-form-item label="变量别名">
        <el-input v-model="dialogForm.l1VariableAlias" placeholder="请输入变量别名" />
      </el-form-item>
      <el-form-item label="变量描述">
        <el-input v-model="dialogForm.l1VariableDescription" placeholder="请输入变量描述" />
      </el-form-item>
      <el-form-item label="数据源">
        <el-select v-model="dialogForm.outDataSource" placeholder="数据源" clearable>
          <el-option v-for="item in dataSourceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="触发标记">
        <el-input v-model="dialogForm.triggerFlag" placeholder="请输入触发标记" />
      </el-form-item>
      <el-form-item label="变量属性">
        <el-input v-model="dialogForm.variableProperty" placeholder="请输入变量属性" />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-switch
          v-model="dialogForm.enable"
          active-color="#13ce66"
          inactive-color="#ff4949"
          inline-prompt
          active-text="是"
          inactive-text="否"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="dialogFormSubmit"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts">
  import { ref, reactive, computed, onMounted, onUnmounted, nextTick, defineComponent } from 'vue';
  import './steelCoilServiceModelCommonStyle.less';
  import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
  import { api } from '/@/api/steelCoilServiceModel/dataAcquisition';

  const dataSourceTypeOptions = ref([
    { label: '宝信sftp长度数据', value: '1' },
    { label: '宝信DB2数据库', value: '2' },
    { label: '宝信restapi实时跟踪数据', value: '3' },
    { label: '宝信SDK实时报警数据', value: '4' },
  ]);

  type DataSourceTypeOptions = {
    value: string;
    label: string;
  };

  const dataSourceType = ref<DataSourceTypeOptions>({ label: '宝信sftp长度数据', value: '1' });

  interface SearchForm {
    productionLine: string;
    l1VariableDescription: string;
    l1VariableName: string;
    l1VariableAlias: string;
    outDataSource: string;
  }

  interface dialogForm {
    indocno: Number;
    productionLine: string;
    areaDescription: string;
    areaCode: string;
    deviceDescription: string;
    deviceCode: string;
    l1VariableDescription: string;
    l1VariableName: string;
    l1AliasDescription: string;
    l1VariableAlias: string;
    outDataSource: string;
    triggerFlag: string;
    variableProperty: string;
    enable: string;
    eigenValue: string;
    toc: string;
    tom: string;
  }

  const dialogFormRule = reactive<any>({
    productionLine: [{ required: true, message: '请输入产线', trigger: 'blur' }],
    areaCode: [{ required: true, message: '请输入区域代码', trigger: 'blur' }],
    deviceCode: [{ required: true, message: '请输入设备代码', trigger: 'blur' }],
    l1VariableName: [{ required: true, message: '请输入变量名', trigger: 'blur' }],
    outDataSource: [{ required: true, message: '请输入数据源', trigger: 'blur' }],
    triggerFlag: [{ required: true, message: '请输入触发标记', trigger: 'blur' }],
    variableProperty: [{ required: true, message: '请输入变量属性', trigger: 'blur' }],
  });

  export default defineComponent({
    name: 'DataDictionary',
    setup() {
      // 表单数据
      const headerSearchForm = reactive<SearchForm>({
        productionLine: '',
        l1VariableDescription: '',
        l1VariableName: '',
        l1VariableAlias: '',
        outDataSource: '',
      });

      // 表格数据
      const tableData = ref([
        {
          indocno: 0,
          productionLine: '',
          areaDescription: '',
          areaCode: '',
          deviceDescription: '',
          deviceCode: '',
          l1VariableDescription: '',
          l1VariableName: '',
          l1AliasDescription: '',
          l1VariableAlias: '',
          outDataSource: '1',
          triggerFlag: '',
          variableProperty: '',
          enable: '0',
          eigenValue: '0',
          toc: '',
          tom: '',
        },
      ]);

      const dialogFormRule = ref<FormInstance>();
      let dialogVisible = ref(false);
      let dialogTitle = ref('');
      const dialogForm = reactive<dialogForm>({
        indocno: 0,
        productionLine: '',
        areaDescription: '',
        areaCode: '',
        deviceDescription: '',
        deviceCode: '',
        l1VariableDescription: '',
        l1VariableName: '',
        l1AliasDescription: '',
        l1VariableAlias: '',
        outDataSource: '1',
        triggerFlag: '',
        variableProperty: '',
        enable: '0',
        eigenValue: '0',
        toc: '',
        tom: '',
      });
      const dialogRef = ref();

      // 分页数据
      const pagination = reactive({
        currentPage: 1,
        pageSize: 10,
        total: tableData.value.length,
      });

      // 窗口大小变化处理
      const handleResize = () => {
        nextTick(() => {
          // 这里可以添加表格自适应高度的逻辑
        });
      };

      // 获取表格数据
      const fetchTableData = async () => {
        try {
          const param = {
            page: {
              pageIndex: pagination.currentPage,
              pageSize: pagination.pageSize,
            },
            dto: headerSearchForm,
          };
          const res = await api.page(param);
          tableData.value = res.data.data.records;
          pagination.currentPage = res.data.data.current;
          pagination.pageSize = res.data.data.size;
          pagination.total = res.data.data.total;
        } catch (error) {
          ElMessage.error('获取数据失败');
        }
      };

      // 查询方法
      const handleSearch = () => {
        pagination.currentPage = 1;
        headerSearchForm.outDataSource = dataSourceType.value.value;
        fetchTableData();
      };

      // 重置方法
      const handleReset = () => {
        (Object.keys(headerSearchForm) as Array<keyof SearchForm>).forEach((key) => {
          headerSearchForm[key] = '';
        });
        handleSearch();
      };

      // 添加方法
      const handleAdd = () => {
        // 这里添加新增逻辑
        dialogVisible.value = true;
        dialogTitle.value = '新增';
      };

      // 编辑方法
      const handleEdit = (row: any) => {
        dialogVisible.value = true;
        dialogTitle.value = '修改';
        Object.assign(dialogForm, { ...row });
        console.log(row.outDataSource);
        // dialogForm.outDataSource = row.outDataSource;
      };

      const cancel = () => {
        dialogVisible.value = false;
        Object.assign(dialogForm, {
          indocno: 0,
          productionLine: '',
          areaDescription: '',
          areaCode: '',
          deviceDescription: '',
          deviceCode: '',
          l1VariableDescription: '',
          l1VariableName: '',
          l1AliasDescription: '',
          l1VariableAlias: '',
          outDataSource: '1',
          triggerFlag: '',
          variableProperty: '',
          enable: '0',
          eigenValue: '0',
          toc: '',
          tom: '',
        });
      };

      const dialogFormSubmit = async () => {
        try {
          if (dialogTitle.value === '修改') {
            api.update(dialogForm);
          } else {
            api.add(dialogForm);
          }
        } catch (error) {
          ElMessage.error('操作数据失败');
        } finally {
          ElMessage.success('操作成功');
          Object.assign(dialogForm, {
            indocno: 0,
            productionLine: '',
            areaDescription: '',
            areaCode: '',
            deviceDescription: '',
            deviceCode: '',
            l1VariableDescription: '',
            l1VariableName: '',
            l1AliasDescription: '',
            l1VariableAlias: '',
            outDataSource: '1',
            triggerFlag: '',
            variableProperty: '',
            enable: '0',
            eigenValue: '0',
            toc: '',
            tom: '',
          });
          dialogVisible.value = false;
          fetchTableData();
        }
      };

      // 删除方法
      const handleDelete = async (row: any) => {
        try {
          // const param = {
          //   indocno: row.indocno,
          // };
          await api.delete(row.indocno);
        } catch (error) {
          ElMessage.error('删除失败');
        } finally {
          fetchTableData();
        }
      };

      // 分页大小变化
      const handleSizeChange = (val: number) => {
        pagination.pageSize = val;
        fetchTableData();
      };

      // 页码变化
      const handleCurrentChange = (val: number) => {
        pagination.currentPage = val;
        fetchTableData();
      };

      const handleClose = (done: () => void) => {
        ElMessageBox.confirm('Are you sure to close this dialog?')
          .then(() => {
            done();
          })
          .catch(() => {
            // catch error
          });
      };

      // 生命周期钩子
      onMounted(() => {
        fetchTableData();
        window.addEventListener('resize', handleResize);
      });

      onUnmounted(() => {
        window.removeEventListener('resize', handleResize);
      });

      return {
        headerSearchForm,
        tableData,
        pagination,
        handleSearch,
        handleReset,
        handleAdd,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        dataSourceTypeOptions,
        // dataSourceType,
        dialogVisible,
        handleClose,
        dialogTitle,
        dialogForm,
        dialogRef,
        cancel,
        dialogFormSubmit,
        dataSourceType,
        dialogFormRule,
      };
    },
  });
</script>
